var md5 = require('../utils/md5.js').MD5;
var default_config = require('../config/deault.js');
var mongoose = require('./mongoose.js').mongoose;
var BlogModel = require('../models/blog.js')(mongoose);
module.exports = {
	getNullBlog:function () {
		return new BlogModel();
	},
	getBlogByJson:function (blog) {
		return new BlogModel(blog);
	},
	findBlogsByUserId:function (pageIndex,_id,callback) {
		var limit = default_config.pageSize;
		var skip = (pageIndex - 1) * limit;
		BlogModel.count({
			user_id:_id
		},function (err,count) {
			if(err){
				callback(false,err,[],0,default_config.pageSize);
			}else{
				BlogModel.find({
					user_id:_id
				}).skip(skip).limit(limit).sort('-update_time').exec(function (err,blogs) {
					if(err){
						callback(false,err,[],count,default_config.pageSize);
					}else {
						callback(true,null,blogs,count,default_config.pageSize);
					}
				});
			}
		});
	},
	findBlogs:function (pageIndex,callback) {
		var limit = default_config.pageSize;
		var skip = (pageIndex - 1) * limit;
		BlogModel.count(function (err,count) {
			if(err){
				callback(false,err,[],0,default_config.pageSize);
			}else{
				BlogModel.find().skip(skip).limit(limit).sort('-update_time').exec(function (err,blogs) {
					if(err){
						callback(false,err,[],count,default_config.pageSize);
					}else {
						callback(true,null,blogs,count,default_config.pageSize);
					}
				});
			}
		});
	},
	addOrUpdate:function (blog,callback) {
		BlogModel.findById(blog._id,function (err,b) {
			if(err){
				callback(false,null,'数据库异常1');
			}else{
				if(b != null){
					//修改
					b.update_time = Date.now();
					b.title = blog.title;
					b.author = blog.author;
					b.tags = blog.tags;
					b.keywords = blog.keywords;
					b.content = blog.content;
					b.zhaiyao = blog.zhaiyao;

					b.save(function (e,blog) {
						if(e){
							callback(false,null,'数据库异常3');
						}else{
							callback(true,blog,'修改');
						}
					});
				}else{
					//新增
					blog.save(function (e,blog) {
						if(e){
							callback(false,null,'数据库异常2');
						}else{
							callback(true,blog,'新增');
						}
					});
				}
				
			}
		});
	},
	findBlogById:function (_id,callback) {
		BlogModel.findById(_id,function (err,blog) {
			if(err){
				callback(false,null);
			}else{
				callback(true,blog);
			}
		});
	},
	readBlog:function (_id,callback) {
		BlogModel.findByIdAndUpdate(_id,{
			$inc:{
				read:1
			}
		},function (err,blog) {
			if(err){
				callback(false,blog);
			}else{
				callback(true,blog);
			}
		});
	},
	zanBlog:function (_id,callback){
		BlogModel.findByIdAndUpdate(_id,{
			$inc:{
				zan:1
			}
		},function (err,blog) {
			if(err){
				callback(false,blog);
			}else{
				callback(true,blog);
			}
		});
	},
	commentBlog:function (_id,callback){
		BlogModel.findByIdAndUpdate(_id,{
			$inc:{
				comment:1
			}
		},function (err,blog) {
			if(err){
				callback(false,blog);
			}else{
				callback(true,blog);
			}
		});
	}
};
